<!DOCTYPE html>
<html>

<head lang='zh'>
	<meta charset='utf-8'>
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta name="renderer" content="webkit" />
	<meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=0" />
	<title>Luckysheet</title>

	<link rel='stylesheet' href='./plugins/css/pluginsCss.css' />
	<link rel='stylesheet' href='./plugins/plugins.css' />
	<link rel='stylesheet' href='./css/luckysheet.css' />
	<link rel='stylesheet' href='./assets/iconfont/iconfont.css' />
	<script src="./plugins/js/plugin.js"></script>

	<!-- rollup luckysheet.js -->
	<script src="./luckysheet.umd.js"></script>

</head>

<body>
	<!-- Non-full screen test -->
	<!-- <div style="position: relative;width: 100%;height: 100%;">

		<div id="luckysheet" style="margin:0px;padding:0px;position:absolute;width:80%;height:500px;left: 20%;top: 200px;bottom:0;right: 0;"></div>
	</div> -->
	
	<div id="luckysheet" style="margin:0px;padding:0px;position:absolute;width:100%;height:100%;left: 0px;top: 0px;"></div>
	<!-- demo feature, non-production use -->
	<script src="./demoData/demoFeature.js"></script>
	<script src="./demoData/sheetFormula.js"></script>
	<script src="./demoData/sheetCell.js"></script>
	<script src="./demoData/sheetConditionFormat.js"></script>
	<script src="./demoData/sheetTable.js"></script>
	<script src="./demoData/sheetComment.js"></script>
	<script src="./demoData/sheetPivotTableData.js"></script>
	<script src="./demoData/sheetPivotTable.js"></script>
	<script src="./demoData/sheetSparkline.js"></script>
	<script src="./demoData/sheetChart.js"></script>
	<script src="./demoData/sheetPicture.js"></script>
	<script src="./demoData/sheetDataVerification.js"></script>
	<script src="./demoData/sheetImages.js"></script>
	<script src="./demoData/sheetAllData.js"></script>

	<script>
		// import sheetFormula from './demoData/sheetFormula.js'
		// import sheetCell from './demoData/sheetCell.js'
		// import sheetConditionFormat from './demoData/sheetConditionFormat.js'
		// import sheetTable from './demoData/sheetTable.js'
		// import sheetComment from './demoData/sheetComment.js'
		// import sheetPivotTableData from './demoData/sheetPivotTableData.js'
		// import sheetPivotTable from './demoData/sheetPivotTable.js'
		// import sheetSparkline from './demoData/sheetSparkline.js'
		// import sheetChart from './demoData/sheetChart.js'
		// import sheetPicture from './demoData/sheetPicture.js'
		// import sheetDataVerification from './demoData/sheetDataVerification.js'

		$(function () {
			// According to the browser language
			var lang = luckysheetDemoUtil.language() === 'zh' ? 'zh' : 'en';
			var isShare = luckysheetDemoUtil.getRequest().share; // '?share=1' opens the collaborative editing mode
			var gridKey = luckysheetDemoUtil.getRequest().gridKey; // workbook id for collaborative editing, or directly define here
            var options = null;

            if(isShare || gridKey){
				// http://localhost:3000/?gridKey=12eyy789-kk45ofid-23737245
				if(!gridKey){
					alert('If gridKey is not provided in the address bar, please add it in the source code')
				}
                options = {
                    container: "luckysheet",
                    lang: lang,
                    allowUpdate:true,
                    updateImageUrl: location.origin + "/luckysheet/api/updateImg",
                    updateUrl: "ws://"+ location.host +"/luckysheet/websocket/luckysheet",
                    gridKey: gridKey,
                    loadUrl: location.origin + "/luckysheet/api/load",
                    loadSheetUrl: location.origin + "/luckysheet/api/loadsheet"
                }
			}else{
                // http://localhost:3000/ 
                options = {
                    container: 'luckysheet',
					lang: lang,
					// pager: {
					// 	pageIndex: 1,
					// 	pageSize: 10,
					// 	total: 50,
					// 	selectOption: [10, 20]
					// },
					forceCalculation:false,
					plugins: ['chart'],
          showinfobar: false,
					fontList:[
						{
						"fontName":"HanaleiFill",
						"url":"./assets/iconfont/HanaleiFill-Regular.ttf"
						},
						{
						"fontName":"Anton",
						"url":"./assets/iconfont/Anton-Regular.ttf"
						},
						{
						"fontName":"Pacifico",
						"url":"./assets/iconfont/Pacifico-Regular.ttf"
						}
					],
          remoteFunction: function(a, back) {// 远程加载数据
            console.log('remoteFunction1================>', a, back)
            setTimeout(function(){
              back(`==>${a}<==`)
            },2000)
          },
          calcSplitRangeFunction:function(formulaCell, calc_funcStr, formulaArray){
            const reg = /\$.*?\$/g
            const result = calc_funcStr.match(reg)
            if (result != null) {
              for (let j = 0; j < result.length; j++) { // 循环区块
                const item = result[j].substring(1, result[j].length - 1)
                let range = luckysheetformula.getcellrange(item, formulaCell.index);
                if (range) {
                  formulaArray.push(range);
                }
              }
            }
          },
          scriptJsFunction:function(txt, r, c, index){// 执行自定义方法
            console.log('scriptJsFunction================>', txt, r, c, index)
            if(txt.indexOf('=random')===0){
              return `==>${Math.random()}`
            }
          },
          verificationFunction: function(txt, item){
            console.log('scriptJsFunction================>', txt, item)
            if(!item){
              return
            }
            if(item.type === 'dropdown' && item.remote === true){
              return 'a,b,c'.split(',')
            }
            if(item.type === 'checkbox' && item.remote === true){
              item.value1=`${Math.random()}`
            }
          },
					hook:{
            printSheet:function(){
              printAll()
            },
						cellDragStop: function (cell, postion, sheetFile, ctx, event) {
			                // console.info(cell, postion, sheetFile, ctx, event);
			            },
						rowTitleCellRenderBefore:function(rowNum,postion,ctx){
							// console.log(rowNum);
						},
						rowTitleCellRenderAfter:function(rowNum,postion,ctx){
							// console.log(ctx);
						},
						columnTitleCellRenderBefore:function(columnAbc,postion,ctx){
							// console.log(columnAbc);
						},
						columnTitleCellRenderAfter:function(columnAbc,postion,ctx){
							// console.log(postion);
						},
						cellRenderBefore:function(cell,postion,sheetFile,ctx){
							// console.log(cell,postion,sheetFile,ctx);
						},
						cellRenderAfter:function(cell,postion,sheetFile,ctx){
							// console.log(postion);
						},
						cellMousedownBefore:function(cell,postion,sheetFile,ctx){
							// console.log(cell,postion,sheetFile,ctx);
              $('#my-sousuo').hide()
              if(postion.r==0 && postion.c==0){
                let searchObj = $('#my-sousuo')
                if(searchObj.length==0){
                  searchObj = $('<div id="my-sousuo" class="iconfont luckysheet-iconfont-sousuo" style="display:none;position:absolute;color:black;z-index:10;cursor:pointer;" />')
                  $('#luckysheet-cell-main').append(searchObj)
                }

                const r = postion.r
                const c = postion.c
                let row = luckysheet.store.visibledatarow[r]
                let row_pre = r == 0 ? 0 : luckysheet.store.visibledatarow[r - 1];
                let col = luckysheet.store.visibledatacolumn[c]
                let col_pre = c == 0 ? 0 : luckysheet.store.visibledatacolumn[c - 1];
                let margeset = luckysheet.menuButton.mergeborer(luckysheet.store.flowdata, r, c);
                if(!!margeset){
                    row = margeset.row[1];
                    row_pre = margeset.row[0];
                    
                    col = margeset.column[1];
                    col_pre = margeset.column[0];
                }
                
                searchObj.show().css({
                  'max-width': col - col_pre,
                  'max-height': row - row_pre,
                  'left': col - 20,
                  'top': row_pre + (row - row_pre - 20) / 2
                })

                luckysheet.store.luckysheet_select_status = true
                luckysheet.store.luckysheet_select_save.length = 0;
                luckysheet.store.luckysheet_select_save.push({
                    "left": col_pre,
                    "width": col - col_pre - 1,
                    "top": row_pre,
                    "height": row - row_pre - 1,
                    "left_move": col_pre,
                    "width_move": col - col_pre - 1,
                    "top_move": row_pre,
                    "height_move": row - row_pre - 1,
                    "row": [r, postion.r_ed],
                    "column": [c, postion.c_ed],
                    "row_focus": r,
                    "column_focus": c
                });
                luckysheet.selectHightlightShow();
                return false
              }
						},
						cellMousedown:function(cell,postion,sheetFile,ctx){
							// console.log(sheetFile);
						},
						sheetMousemove:function(cell,postion,sheetFile,moveState,ctx){
							// console.log(cell,postion,sheetFile,moveState,ctx);
						},
						sheetMouseup:function(cell,postion,sheetFile,moveState,ctx){
							// console.log(cell,postion,sheetFile,moveState,ctx);
						},
						cellAllRenderBefore:function(data,sheetFile,ctx){
							// console.info(data,sheetFile,ctx)
						},
						updated:function(operate){
							console.info('updated',operate)
						},
						cellUpdateBefore:function(r,c,value,isRefresh){
							// console.info('cellUpdateBefore',r,c,value,isRefresh)
						},
						cellUpdated:function(r,c,oldValue, newValue, isRefresh){
							// console.info('cellUpdated',r,c,oldValue, newValue, isRefresh)
              // newValue._random = new Date().getTime() + ''
              // newValue.v = (newValue.v || '') + newValue._random
              // newValue.m = (newValue.m || '') + newValue._random
						},
						sheetActivate:function(index, isPivotInitial, isNewSheet){
							// console.info(index, isPivotInitial, isNewSheet)
						},
						rangeSelect:function(index, sheet){
							// console.info(index, sheet)
						},
						commentInsertBefore:function(r, c){
							// console.info(r, c)
						},
						commentInsertAfter:function(r, c, cell){
							// console.info(r, c, cell)
						},
						commentDeleteBefore:function(r, c, cell){
							// console.info(r, c, cell)
						},
						commentDeleteAfter:function(r, c, cell){
							// console.info(r, c, cell)
						},
						commentUpdateBefore:function(r, c, value){
							// console.info(r, c, value)
						},
						commentUpdateAfter:function(r, c, oldCell, newCell ){
							// console.info(r, c, oldCell, newCell)
						},
						cellEditBefore:function(range ){
							// console.info(range)
						},
						workbookCreateAfter:function(json){
							// console.info(json)
						},
						rangePasteBefore:function(range,data){
							// console.info('rangePasteBefore',range,data)
							// return false; //Can intercept paste
						},
            keyDownBefore:function(param){
              console.log('***************',param)
              if (param.event.keyCode === 229) {
                console.log('不能输入：2')
                luckysheet.setCellValue(param.r, param.c, '不能输入：2')
                return false
              }
            }
						

					},
					data: 
					[sheetCell,sheetFormula,sheetConditionFormat,sheetSparkline,sheetTable,sheetComment,sheetPivotTableData,sheetPivotTable,sheetChart,sheetPicture,sheetDataVerification]
				}
			}
			options.loading={
				image:()=>{
					return `<svg viewBox="25 25 50 50" class="circular">
					<circle cx="50" cy="50" r="20" fill="none"></circle>
					</svg>`
				},
				imageClass:"loadingAnimation"
			}
			options.cellRightClickConfig = {
				customs: [{
					title: 'test',
					onClick: function (clickEvent, event, params) {
						console.log('function test click', clickEvent, event, params)
					}
				}]
			}
      options.data=[{
        name: 'sheet1'
        // images: sheetImages
      }]
      // options.data = sheetAllData.data
			luckysheet.create(options);
			})

      function printAll(){
        const rowCol = getExcelRowColumn()
        if(rowCol.row[0]===null){
          return
        }
        console.log('============>rowCol',rowCol)
        // luckysheet.setRangeFormat("bd", {borderType: "border-right",style: "1", color: "#ff0000"}, rowCol)
        luckysheet.setRangeFormat("bg", "#fff000", {range:rowCol})
        const img = luckysheet.getScreenshot({range:rowCol})
        console.log('============>print',img)
        // downloadBase64Img(img)
      }

      // 获取表格中包含内容的row，column
      function getExcelRowColumn() {
        const sheetData = luckysheet.getSheetData();
        let objRowColumn = {
          row: [null,null], //行
          column: [null,null], //列
        };
        sheetData.forEach((item, index) => {
          //行数
          item.forEach((it, itemIndex) => {
            if (it !== null) {
              if (objRowColumn.row[0] === null) {
                objRowColumn.row[0] = index; // row第一位
              }
              objRowColumn.row[1] = index; //row第二位
              
              if(objRowColumn.column[0] === null){
                objRowColumn.column[0] = itemIndex
                objRowColumn.column[1] = itemIndex
              }else{
                objRowColumn.column[0] = objRowColumn.column[0]>itemIndex?itemIndex:objRowColumn.column[0]
                objRowColumn.column[1] = objRowColumn.column[1]<itemIndex?itemIndex:objRowColumn.column[1]
              }
            }
          });
        });
        return objRowColumn;
      }

      function downloadBase64Img(content) {
        if (content.indexOf(';base64,') < 0) {
          return
        }
        const parts = content.split(';base64,')
        const contentType = parts[0].split(':')[1]
        const raw = window.atob(parts[1])
        const rawLength = raw.length
        const uInt8Array = new Uint8Array(rawLength)
        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i)
        }
        const blob = new Blob([uInt8Array], {
          type: contentType
        })
      
        const aLink = document.createElement('a')
        // const evt = document.createEvent('HTMLEvents')
        // evt.initEvent('click', true, true) // initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
        aLink.download = new Date().getTime() + '.' + (contentType.split('/')[1])
        aLink.href = URL.createObjectURL(blob)
        aLink.click()
        aLink.remove()
      }
	</script>
<style>
	/* 自定义loading演示样式 */
	@keyframes loading-rotate {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	@keyframes loading-dash {
		0% {
			stroke-dasharray: 1, 200;
			stroke-dashoffset: 0;
		}

		50% {
			stroke-dasharray: 90, 150;
			stroke-dashoffset: -40px;
		}

		100% {
			stroke-dasharray: 90, 150;
			stroke-dashoffset: -120px;
		}
	}

	.loadingAnimation {
		width: 3em;
		height: 3em;
		animation: loading-rotate 2s linear infinite;
	}

	.loadingAnimation circle {
		animation: loading-dash 1.5s ease-in-out infinite;
		stroke-dasharray: 90, 150;
		stroke-dashoffset: 0;
		stroke-width: 2;
		stroke: currentColor;
		stroke-linecap: round;
	}
</style>
</body>

</html>
